var app = getApp();
var util = require('../../util/util.js');
const MAX_WORDS_NUM = 140
const MAX_IMG_NUM = 3
const db = wx.cloud.database()
let content = ''
let title = ''
let userInfo = {}
let signUpForm = []
let numMan = ['0','0']
let autoStopTime=''
let zongRenShu = ''
let daiBao = ''
Page({ 

  data: {
    selectPhoto: true,  //是否显示图片加号
    images: [],         //图片数组
    showManNum: false,  //是否显示人数限制
    stoptime: false,    //是否显示截止日期
    sort: false,        //是否排序
    showName: false,
    setNum: false,      //是否显示人数限制弹出层
    setForm: false,
    activeContent:'',
    formArr: [],
    nums: '总人数无限制,不可帮他人报名',
    newItem: '',        //自定义格式
    items: [            //报名格式 
      { name: '姓名', value: '姓名' },
      { name: '手机号', value: '手机号' },
      { name: '微信号', value: '微信号' },
      { name: '地址', value: '地址' },
      { name: '性别', value: '性别' },
      { name: '身高', value: '身高' },
      { name: '身份证号', value: '身份证号' }
    ],
    pass: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    userInfo = options
  },


  inputTitle(event) {     //输入标题
    console.log(event.detail.value) 
    title = event.detail.value
  },

  inputContent(event) {   //输入内容
    console.log(event.detail.value)
   
    content = event.detail.value
  },

  onChooseImage() {  //选择图片
    let max = MAX_IMG_NUM - this.data.images.length
    wx.chooseImage({
      count: max, //还可以选多少张
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(res)
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
        max = MAX_IMG_NUM - this.data.images.length
        this.setData({
          selectPhoto: max <= 0 ? false : true
        })
      },
    })
  },


  onDelImage(event) {   //删除图片
    this.data.images.splice(event.target.dataset.index, 1)
    this.setData({
      images: this.data.images
    })
    if (this.data.images.length == MAX_IMG_NUM - 1) {
      this.setData({
        selectPhoto: true,
      })
    }
  },

  onPreviewImage(event) {   //预览图片
    wx.previewImage({
      urls: this.data.images,
      current: event.target.dataset.imgsrc
    })
  },   




  //报名格式---------------
  showSetForm(){
    this.setData({
      setForm: true,
      pass: false
    })
  },
  checkboxChange: function (e) {
    signUpForm = e.detail.value
  },

  inputItem(e) {
    this.data.newItem = e.detail.value
  },
  addItem() {
    if (this.data.newItem.trim() == '') {
      wx.showModal({
        title: '字段名称不能为空',
        content: '',
      })
      return
    } 
    let newItems = this.data.items
    newItems.push({ name: this.data.newItem, value: this.data.newItem })
    this.setData({
      items: newItems,
      newItem: '' 
    })
  },

  saveForm(){
    this.setData({
      setForm: false,
      formArr: signUpForm,
      pass: true
    })
  },



  //第三个框-----------------
  selectManNum(e){   //人数限制switch是否选中
    this.setData({
      showManNum: !this.data.showManNum
    })
  },

  showNumView(){
    this.setData({
      setNum: true,
      pass: false
    })
  },


  inputNum1(e) {
    
    zongRenShu = e.detail.value
    numMan[0] = zongRenShu
  },
  inputNum2(e) {
    console.log(e)
    daiBao = e.detail.value
    numMan[1] = daiBao
  },

  close() {
    if (zongRenShu < 0 || zongRenShu === '0') {
      wx.showModal({
        title: '总人数必须大于0',
        content: '',
      })
      return
    }
    if (daiBao < 0) {
      wx.showModal({
        title: '代报人数不能小于0',
        content: '',
      })
      return
    }
    if (numMan[0]>0){
    if(numMan[0]<numMan[1]){
      wx.showModal({
        title: '代报人数不能大于总人数',
        content: '',
      })
      return
    }}
   
    let a = numMan[0] == '0' ? '总人数无限制,' : `总人数为${numMan[0]}人,`
    let b = numMan[1] == '0' ? '不可帮他人报名' : `可帮${numMan[1]}人报名`
    console.log(a)
    console.log(b)
    let ab = a+b
    console.log(ab)
    this.setData({
      setNum: false,
      nums: ab,
      pass: true
    })
  },

 
  isSort() {       //排序switch是否选中
    this.setData({
      sort: !this.data.sort
    })
  },

  stopTime() {      //截止时间switch是否选中
    this.setData({
      stoptime: !this.data.stoptime
    })
  },

  setTime(e){
    console.log(e.detail)
    autoStopTime = e.detail
  },

  hiddenName() {    //隐藏名单switch是否选中
    this.setData({
      showName: !this.data.showName
    })
  },


  relay(){
    if(title.trim()==''){
      wx.showModal({
        title: '活动主题不能为空',
        content: '',
      })
      return
    } else if (content.trim() == '') {
      wx.showModal({
        title: '活动内容不能为空',
        content: '',
      })
      return
    }else if (this.data.formArr.length==0) {
      wx.showModal({
        title: '报名格式未设置',
        content: '',
      })
      return
    }  



    let snum = []
    if (this.data.showManNum){
      snum = numMan
    }else{
      snum = ['0','0']
    }
    console.log(snum)

    
    let auto = ''
    if (this.data.stoptime){
       auto = autoStopTime == '' ? util.formatTime(new Date()) : autoStopTime
    }else{
       auto = ''
    }


    wx.showLoading({
      title: '发起接龙中',
      mask: true
    })

    let promiseArr = []
    let fileIds = []
    for (let i = 0, len = this.data.images.length; i < len; i++) {
      let p = new Promise((resolve, reject) => {
        let item = this.data.images[i]
        //获取图片后缀
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({
          cloudPath: 'signUp/' + Date.now() + '-' + Math.random() * 1000000 + suffix,
          filePath: item,
          success: (res) => {
            console.log(res)
            fileIds = fileIds.concat(res.fileID)
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })

      promiseArr.push(p)
    }
    Promise.all(promiseArr).then((res) => {
      db.collection('signUp').add({
        data: {
          ...userInfo,
          title,
          content,
          snum,
          auto,
          isEnd: '',
          img: fileIds,
          formArr: this.data.formArr,
          sort: this.data.sort,
          showName: this.data.showName,
          createTime: db.serverDate()  //服务端时间
        }
      }).then((res) => {
        wx.hideLoading()
        wx.showToast({
          title: '发起接龙成功',
        })
        wx.navigateBack()
        const pages = getCurrentPages()
        const prePage = pages[pages.length - 2]

      })
    }).catch((err) => {
      wx.hideLoading()
      wx.showToast({
        title: '发起接龙失败',
      })
    })
  }

  
})